<style scoped>
    .rui-query-form{
        padding-bottom: 15px;
    }
    .rui-query-form-row{
        width: 100%
    }
    .rui-query-form-row:after{
        content:" ";
        display:block;
        height:0;
        visibility:hidden;
        clear:both;
    }
    .rui-query-form-item{
        float: left;
    }
    .applyQuerySearchRow{
        padding: 5px 24px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .applyQuerySearchItem /deep/ .ivu-form-item-content > div {
        display: flex;
        align-items: center;
    }
    .applyQuerySearchItem /deep/ .ivu-form-item {
        margin-bottom: 0;
    }
    .applyQuerySearchMore {
        /*padding-top: 16px;*/
        /*padding-right: 56px;*/
        /*padding: 16px 80px 0 24px;*/
        margin-top: 16px;
        padding: 16px 24px;
        background-color: #fff;
        box-shadow: 0 0 4px 2px rgba(0, 0, 0, 0.04);
        transition: all .3s linear;
    }
    .applyQuerySearchMoreRow {
        width: 100%;
        display: flex;
      flex-flow: row wrap;
      justify-content: flex-start;
      align-items: center;
    }
</style>
<template>
    <div :style="{width}"  class="rui-query-form">
        <Row v-show="_defineIdsFinished">
            <Form :hide-required-mark="false" @submit.native.prevent="preventSubmit" @keydown.enter.native="handleSearch" :label-colon="true" :model="formData"  ref="ruiQuery" >
                <template v-if="isApplyQuery">
                    <div class="applyQuerySearchRow" :key="defineIndex" v-for="(defineInfo,defineIndex)  in queryDefines">
                        <div class="applyQueryHead">
                            <slot v-if="defineIndex === 0" name="applyQueryHead"></slot>
                        </div>
                        <div class="applyQuerySearchItem" :key="itemIndex"  v-for="(item,itemIndex) in defineInfo">
                                <FormItem
                                    :prop="item.key"
                                    :class="item.key"
                                    :ref="`_rui_item_`+item.key"
                                    :required="item.require"
                                    :rules="formRules[item.key]"
                                    v-if="formKeys.includes(item.key)&&!formHideKeys.includes(item.key)">
                                    <rui-item
                                        :formData="formData"
                                        :formHasSlotKeys="formHasSlotKeys"
                                        :formRules="formRules"
                                        :formSimpleItem="[]"
                                        :formSlots="formSlots"
                                        :item="item">
                                        <a v-if="moreRows.length>0&&defineIndex===(queryDefines.length-1)&&itemIndex===(defineInfo.length-1)"
                                           :style="{display:'block',width:'40px',lineHeight: '24px',marginLeft: '16px'}"  @click="dropDown">{{dropDownContent}}
                                            <Icon :type="dropDownIcon"></Icon>
                                        </a>
                                    </rui-item>
                                </FormItem>
                        </div>
                    </div>
                    <div v-if="drop" class="applyQuerySearchMore table-card">
                        <div  class="applyQuerySearchMoreRow" :key="defineIndex+'-more'" v-for="(defineInfo,defineIndex)  in moreDefines">
                            <div class="rui-query-form-item" :key="itemIndex"  v-for="(item,itemIndex) in defineInfo">
                                <FormItem
                                        :label="item.title"
                                        :label-width="item.labelWidth?item.labelWidth:labelWidth"
                                        :prop="item.key"
                                        :ref="`_rui_item_`+item.key"
                                        :required="item.require"
                                        :rules="formRules[item.key]"
                                        v-if="formKeys.includes(item.key)&&!formHideKeys.includes(item.key)">
                                        <rui-item
                                            :formData="formData"
                                            :formHasSlotKeys="formHasSlotKeys"
                                            :formRules="formRules"
                                            :formSimpleItem="[]"
                                            :formSlots="formSlots"
                                            :item="item">
                                        </rui-item>
                                    </FormItem>
                            </div>
                        </div>
                        <div style="text-align: center">
                            <Button @click="handleSearch" type="primary">查询</Button>
                            <Button @click="handleReset">重置</Button>
                        </div>
                    </div>
                </template>
                <template v-else>
                <div class="rui-query-form-row" :key="defineIndex" v-for="(defineInfo,defineIndex)  in queryDefines">
                    <div class="rui-query-form-item" :key="itemIndex"  v-for="(item,itemIndex) in defineInfo">
                        <div >
                            <FormItem
                                :label="item.title"
                                :label-width="item.labelWidth?item.labelWidth:labelWidth"
                                :prop="item.key"
                                :ref="`_rui_item_`+item.key"
                                :required="item.require"
                                :rules="formRules[item.key]"
                                v-if="formKeys.includes(item.key)&&!formHideKeys.includes(item.key)">
                                <rui-item
                                    :formData="formData"
                                    :formHasSlotKeys="formHasSlotKeys"
                                    :formRules="formRules"
                                    :formSimpleItem="[]"
                                    :formSlots="formSlots"
                                    :item="item">
                                    <a v-if="moreRows.length>0&&defineIndex===(queryDefines.length-1)&&itemIndex===(defineInfo.length-1)&&!drop"
                                       :style="{display:'block',width:'40px',lineHeight: '32px',position: 'absolute',top: 0,left: ((item.width?item.width:200)+5)+'px'}"  @click="dropDown">{{dropDownContent}}
                                        <Icon :type="dropDownIcon"></Icon>
                                    </a>
                                </rui-item>
                            </FormItem>
                        </div>
                    </div>
                </div>
                <div v-if="drop" >
                    <div  class="rui-query-form-row" :key="defineIndex+'-more'" v-for="(defineInfo,defineIndex)  in moreDefines">
                        <div class="rui-query-form-item" :key="itemIndex"  v-for="(item,itemIndex) in defineInfo">
                            <div  >
                                <FormItem
                                    :label="item.title"
                                    :label-width="item.labelWidth?item.labelWidth:labelWidth"
                                    :prop="item.key"
                                    :ref="`_rui_item_`+item.key"
                                    :required="item.require"
                                    :rules="formRules[item.key]"
                                    v-if="formKeys.includes(item.key)&&!formHideKeys.includes(item.key)">
                                    <rui-item
                                        :formData="formData"
                                        :formHasSlotKeys="formHasSlotKeys"
                                        :formRules="formRules"
                                        :formSimpleItem="[]"
                                        :formSlots="formSlots"
                                        :item="item">
                                        <a v-if="defineIndex===(moreDefines.length-1)&&itemIndex===(defineInfo.length-1)&&drop"
                                           :style="{display:'block',width:'40px',lineHeight: '32px',position: 'absolute',top: 0,left: ((item.width?item.width:200)+5)+'px'}"  @click="dropDown">{{dropDownContent}}
                                            <Icon :type="dropDownIcon"></Icon>
                                        </a>
                                    </rui-item>
                                </FormItem>
                            </div>
                        </div>
                    </div>
                </div>
                <Col :span="maxCol">
                    <div style="text-align: center">
                        <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button @click="handleReset" icon="ios-trash-outline">重置</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                    </div>
                </Col>
                </template>
            </Form>
        </Row>
    </div>
</template>
<script>
    import ruiMixin from '../../mixin/rui-global-components';
    import ruiEleMixin from '../../mixin/rui-element-mixin'
    import RuiItem from '_c/rui-auto/rui-form/src/item'
    import validator from '../../validate/rules'
    import dateUtil from '_c/iview/utils/date';

    export default {
        name: 'rui-query',
        mixins: [ruiMixin,ruiEleMixin],
        components: {
            RuiItem
        },
        provide() {
            return {
                RuiForm: this
            };
        },
        props: {
            labelWidth: {
                type: Number,
                require: false,
                default: 150
            },
            queryRows: {
                type: Array,
                require: true
            },
            moreRows: {
                type: Array,
                require: false,
                default: ()=> []
            },
            width:{
                type:String,
                default:'100%'
            },
            isApplyQuery:{
              type: Boolean,
              default: false
            },
            beforeChange:Function,
            afterChange:Function,
            query:Function
        },
        data() {
            return {
                dropDownContent:'更多',
                drop:false,
                dropDownIcon: "ios-arrow-down",
                defaultFormData: {},
                formData: {},
                backUpData:{},
                queryDefines: [],
                moreDefines: [],
                formItems: [],
                formRules: {},
                formSlots: {},
                formHasSlotKeys: [],
                formRequiredKeys: [],
                formKeys: [],
                formHideKeys: [],
                rebuild: false,
                formItemsType: {},
                maxCol:22
            }
        },
        methods: {
            preventSubmit(){
                return false;
            },
            prepareDefine(rows,defines){
                let self = this;
                rows.forEach(row=>{
                    let defineInfo = [];
                    if (row.fields && row.fields.length > 0) {
                        if(row.totalSpan&&row.totalSpan<self.maxCol){
                            self.maxCol = row.totalSpan;
                        }
                        let span = parseInt((row.totalSpan?row.totalSpan:22)/row.fields.length+'');
                        row.fields.forEach(fieldKey => {
                            if (row.defineId) {
                                if (row.slots && row.slots.length > 0) {
                                    row.slots.forEach(slot => {
                                        self.formSlots[slot.key] = slot.slotName;
                                        self.formHasSlotKeys.push(slot.key);
                                    })
                                }
                                let item = self.RuiPage.getColumnDefine(row.defineId,fieldKey);
                                item.span = span;
                                self.formItems.push(item);
                                // 表格所有key
                                if (!self.formKeys.includes(item.key)) {
                                    self.formKeys.push(item.key);
                                } else {
                                    throw Error(item.key + '重复')
                                }
                                //设置默认精度
                                if (Number.isNaN(item.scale)) {
                                    item.scale = 2;
                                }
                                //设置默认类型 为text
                                if (!item.type || item.type == '') {
                                    item.type = 'text';
                                }
                                item._type = item.type;
                                //设置默认placeholder
                                if (!item.placeholder || item.placeholder == '') {
                                    item.placeholder = '请输入' + item.title;
                                }
                                //校验规则处理
                                //初始化规则数组
                                let itemRules = [];
                                if (item.type === 'text' || item.type == 'password' || item.type == 'textarea') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'url') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        message: item.title + '值不能为空'
                                    })
                                    itemRules.push({type: 'url', message: '网址格式不正确'})
                                } else if (item.type == 'email') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        message: item.title + '值不能为空'
                                    })
                                    itemRules.push({type: 'email', message: '邮箱格式不正确'})
                                } else if (item.type == 'mobile') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        message: item.title + '值不能为空'
                                    })
                                    itemRules.push({message: '手机号格式不正确', validator: validator.mobileValidator})
                                } else if (item.type == 'radio') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        trigger: 'change',
                                        message: '请选择一项'
                                    })
                                } else if (item.type == 'checkbox') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.arrayValidator,
                                        trigger: 'change',
                                        message: '请选择一项'
                                    })
                                } else if (item.type == 'date') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.dateValidator,
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'dateRange') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.dateRangeValidator,
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'datetime') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.dateValidator,
                                        trigger: 'change',
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'datetimeRange') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.dateRangeValidator,
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'time') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.dateValidator,
                                        trigger: 'change',
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'timeRange') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.dateRangeValidator,
                                        trigger: 'change',
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'singleSelect') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        message: '请至少选择一项'
                                    })
                                } else if (item.type == 'multipleSelect') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.arrayValidator,
                                        message: '请至少选择一项'
                                    })
                                } else if (item.type == 'number') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        message: item.title + '值不能为空'
                                    })
                                } else if (item.type == 'currency') {
                                    itemRules.push({
                                        required: item.require,
                                        validator: validator.stringValidator,
                                        message: item.title + '值不能为空'
                                    })
                                }
                                //设置格式样式
                                if (!item.format) {
                                    if (item.type == 'date' || item.type == 'dateRange') {
                                        item.format = 'yyyy-MM-dd';
                                    } else if (item.type == 'datetime' || item.type == 'datetimeRange') {
                                        item.format = 'yyyy-MM-dd HH:mm:ss';
                                    } else if (item.type == 'time' || item.type == 'timeRange') {
                                        item.format = 'HH:mm:ss';
                                    }
                                }
                                //设定参数
                                self.formItemsType[item.key] = {type: item.type, format: item.format};
                                self.formRules[item.key] = itemRules;
                                //添加自定规则
                                if (item.rules && Array.isArray(item.rules)) {
                                    self.formRules[item.key].push(...item.rules)
                                }

                                //默认值处理
                                if (item.type == 'dateRange' || item.type == 'datetimeRange' || item.type == 'timeRange') {
                                    self.$set(self.formData, item.key, []);
                                    self.$set(self.defaultFormData, item.key, []);
                                    self.$set(self.backUpData, item.key, []);
                                } else if (item.type == 'checkbox' || item.type == 'multipleSelect') {
                                    self.$set(self.formData, item.key, []);
                                    self.$set(self.defaultFormData, item.key, []);
                                    self.$set(self.backUpData, item.key, []);
                                } else if (item.type == 'currency') {
                                    item.dataFormater = this.currencyFormat
                                    self.$set(self.formData, item.key, null);
                                    self.$set(self.defaultFormData, item.key, null);
                                    self.$set(self.backUpData, item.key, null);
                                } else if (item.type == 'number') {
                                    item.dataFormater = this.numberFormat
                                    self.$set(self.formData, item.key, null);
                                    self.$set(self.defaultFormData, item.key, null);
                                    self.$set(self.backUpData, item.key, null);
                                } else if (item.type == 'date') {
                                    self.$set(self.formData, item.key, null);
                                    self.$set(self.defaultFormData, item.key, null);
                                    self.$set(self.backUpData, item.key, null);
                                } else {
                                    if (item.default) {
                                        self.$set(self.formData, item.key, item.default);
                                        self.$set(self.defaultFormData, item.key, item.default);
                                        self.$set(self.backUpData, item.key, item.default);
                                    } else {
                                        self.$set(self.formData, item.key, '');
                                        self.$set(self.defaultFormData, item.key, '');
                                        self.$set(self.backUpData, item.key, '');
                                    }
                                }
                                //动态设置watch
                                if(self.beforeChange||self.afterChange){
                                    self.$watch('formData.'+item.key,
                                        function(afterValue,beforeValue){
                                            if(self.beforeChange) {
                                                const checkResult = self.beforeChange(item.key
                                                    , self.formatData(item.key, beforeValue, item.format)
                                                    , self.formatData(item.key, afterValue, item.format));
                                                if (!checkResult && afterValue !== self.backUpData[item.key]) {
                                                    self.$nextTick(() => {
                                                        self.setFiledValue(item.key, self.backUpData[item.key])
                                                    });
                                                } else {
                                                    if (self.afterChange) {
                                                        self.afterChange(item.key, self.formatData(item.key, afterValue, item.format));
                                                    }
                                                }
                                            }else{
                                                if (self.afterChange) {
                                                    self.afterChange(item.key, self.formatData(item.key, afterValue, item.format));
                                                }
                                            }
                                        },
                                        {deep: true}
                                    )
                                }
                                self.prepareDicInfo(item);
                                defineInfo.push(item);
                            }
                        });
                    }
                    defines.push(defineInfo);
                })
            },
            init() {
                if (!this.queryRows || this.queryRows.length == 0) {
                    throw Error('ruiQuery组件queryCols定义不合法');
                }
                let self = this;

                this.prepareDefine(this.queryRows,this.queryDefines);
                if (this.moreRows&&this.moreRows.length > 0) {
                    this.prepareDefine(this.moreRows, this.moreDefines);
                }
                //校验类型是否输入组件定义类型
                self.formItems.forEach(item => {
                    if (!self.allTypes.includes(item.type)) {
                        throw Error(item.key + '[type]定义不合法,请在' + self.allTypes + '中选择');
                    }
                });
                this.$emit('ruiFormFinished');
            },
            formatData(type,value,format){
                if (type == 'date' || type == 'datetime' || type == 'time') {
                    if (value && value instanceof Date) {
                        return  dateUtil.format(value, format)
                    }
                } else if (type == 'dateRange' || type == 'datetimeRange' || type == 'timeRange') {
                    if (value && (Array.isArray(value))) {
                        let temp = [];
                        value.forEach(dateItem => {
                            if (dateItem && dateItem instanceof Date) {
                                temp.push(dateUtil.format(dateItem, format))
                            } else {
                                temp.push(dateItem)
                            }
                        })
                        return  temp;
                    }
                }
                return value;
            },
            updateFormData(data) {
                this.formData = data;
            },
            callValidate(key){
                let self = this;
                if(!self.formHideKeys.includes(key)){
                    self.$nextTick(()=>{
                        this.$refs['ruiQuery'].validateField(key,errors=>{

                        });
                    })
                }
            },
            setAllFieldRequired(required) {
                let self = this;
                this.formKeys.forEach(key => {
                    self.formItems.forEach(item => {
                        item.require = required;
                        (self.formRules[item.key])[0].required = required
                    });
                    self.callValidate(key);
                })
            },
            setAllFieldReadOnly(readOnly) {
                let self = this;
                this.formKeys.forEach(key => {
                    self.setFieldReadOnly(key, readOnly);
                })
            },
            setFiledHide(key, hide) {
                let self = this;
                if (!hide) {
                    if (self.formHideKeys.includes(key)) {
                        let index = self.formHideKeys.indexOf(key);
                        if (index > -1) {
                            self.formHideKeys.splice(index, 1);
                        }
                    }
                } else {
                    if (!self.formHideKeys.includes(key)) {
                        self.formHideKeys.push(key);
                    }
                }
            },
            setFieldRequired(key, required) {
                let self = this;
                if (this.formKeys.includes(key)) {
                    self.formItems.forEach(item => {
                        if (item.key == key) {
                            item.require = required;
                            self.callValidate(key);
                        }
                    });
                    (self.formRules[key])[0].required = required
                }
            },
            setFieldReadOnly(key, readOnly) {
                if (this.formKeys.includes(key)) {
                    if (!this.formSimpleItem.includes(key) && readOnly) {
                        this.formSimpleItem.push(key);
                    } else if (this.formSimpleItem.includes(key) && !readOnly) {
                        let index = this.formSimpleItem.indexOf(key);
                        this.formSimpleItem.splice(index, 1);
                    }
                }
            },
            setFiledValue(key, value) {
                this.formData[key] = value;
            },
            getFormData(resetPage=false) {
                let rtn = this.clone(this.formData);
                let self = this;
                Object.keys(this.formData).forEach(key => {
                    if(self.formKeys.includes(key)) {
                        let {type, format} = self.formItemsType[key];
                        if (type == 'date' || type == 'datetime' || type == 'time') {
                            if (rtn[key] && rtn[key] instanceof Date) {
                                rtn[key] = dateUtil.format(rtn[key], format)
                            }
                        } else if (type == 'dateRange' || type == 'datetimeRange' || type == 'timeRange') {
                            if (rtn[key] && (Array.isArray(rtn[key]))) {
                                let temp = [];
                                rtn[key].forEach(dateItem => {
                                    if (dateItem && dateItem instanceof Date) {
                                        temp.push(dateUtil.format(dateItem, format))
                                    } else {
                                        temp.push(dateItem)
                                    }
                                })
                                rtn[key] = temp;
                            }
                        }
                    }
                })
                if(self.refComponent){
                    let pageInfo = self.refComponent.getPageInfo();
                    if(resetPage){
                        pageInfo = self.refComponent.resetPageInfo(1,pageInfo.pageSize);
                    }
                    return {
                        pageNumber:pageInfo.pageNumber,
                        pageSize:pageInfo.pageSize,
                        condition:rtn,
                    }
                }
                return {
                    pageNumber:1,
                    pageSize:10,
                    condition:rtn,
                };
            },
            handleSearch(){
                if(this.query) {
                    this.$refs['ruiQuery'].validate((valid) => {
                        if (valid) {
                            this.query(this.getFormData(true));
                        } else {
                            this.$Message.error("输入值不合法");
                        }
                    })
                }else{
                    this.$Message.error("查询函数未设置");
                }
            },
            handleReset(){
                let self = this;
                this.backUpData = this.clone(this.defaultFormData)
                this.formData = this.clone(this.defaultFormData)
                this.$refs['ruiQuery'].resetFields();
                this.$nextTick(()=>{
                    if(self.refComponent){
                        self.refComponent.resetData();
                    }else{
                        this.query({pageNumber:1, pageSize:10, condition: {}});
                    }
                });
            },
            dropDown() {
                if (this.drop) {
                    this.dropDownContent = "更多";
                    this.dropDownIcon = "ios-arrow-down";
                } else {
                    this.dropDownContent = "收起";
                    this.dropDownIcon = "ios-arrow-up";
                }
                this.drop = !this.drop;
            },
            calDependIds(){
                let ids=[];
                this.queryRows.forEach(row=>{
                    if(!ids.includes(row.defineId)){
                        ids.push(row.defineId)
                    }
                })
                this.moreRows.forEach(row=>{
                    if(!ids.includes(row.defineId)){
                        ids.push(row.defineId)
                    }
                })
                return ids;
            }
        },
        computed: {

        },
        watch: {

        },
        mounted() {
        },
        beforeMount() {
            // this.init();
        }
    }
</script>
